package com.example.mysampleapp.fragment;

import android.app.Fragment;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.RadioGroup;
import android.widget.RadioGroup.OnCheckedChangeListener;

import com.example.myfirstapp.R;
import com.example.mysampleapp.OnSelectedBookChangeListener;

public class BookListFragment extends Fragment implements
		OnCheckedChangeListener {

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		View viewHierarchy = inflater.inflate(R.layout.fragment_book_list,
				container, false);
		RadioGroup group = (RadioGroup) viewHierarchy
				.findViewById(R.id.chapterSelectGroup);
		group.setOnCheckedChangeListener(this);
		return viewHierarchy;
	}

	@Override
	public void onCheckedChanged(RadioGroup group, int checkedId) {
		// Translate radio button to book index
		int bookIndex = translateIdToIndex(checkedId);
		// Get parent Activity and send notification
		OnSelectedBookChangeListener listener = (OnSelectedBookChangeListener) getActivity();
		listener.onSelectedBookChanged(bookIndex);
	}

	int translateIdToIndex(int id) {
		int index = -1;
		switch (id) {
		case R.id.chapter_1:
			index = 0;
			break;
		case R.id.chapter_2:
			index = 1;
			break;
		case R.id.chapter_3:
			index = 2;
			break;
		case R.id.chapter_4:
			index = 3;
			break;
		case R.id.chapter_5:
			index = 4;
			break;
		}
		return index;
	}
}
